import React, { useEffect, useRef, useState } from "react";
import "./index.css";
import Title from "../../component/Title";
import LineChart from "../../component/Line";
import { Button, DatePicker, Segmented, Empty, Popover, message } from "antd";
import dayjs from "dayjs";
import request from "../../axios";
import { InfoCircleOutlined } from "@ant-design/icons";
import { useSelector } from "react-redux";
import { PullToRefreshify } from "react-pull-to-refreshify";

const { RangePicker } = DatePicker;

// 定义类型
type Merchant = {
  merchantName: string;
  merchantId: string | number;
};

type Merchants = {
  data?: Merchant[];
};

type Device = {
  deviceAlias: string;
  onlineStatus: string;
  cgid: string;
  loginCity: string;
  deviceModelCode?: string | null;
};

type Recipe = {
  recipeName: string;
  cookTimes?: number;
  cookSpecCopies?: number;
};

type TitleEnumType = {
  [key: string]: string;
};

const titleEnum: TitleEnumType[] = [
  {
    name: "调料校准",
    value: "totalSeasoningAdjustNum",
    title: "调料校准：统计起止日期内进行调料校准的调料次数",
  },
  {
    name: "调料测试",
    value: "totalSeasoningTestNum",
    title:
      "调料测试：统计起止日期内进行调料测试的调料次数，调料测试暂时只支持个别设备",
  },
  {
    name: "调料检查",
    value: "totalSeasoningInspectNum",
    title: "调料检查：统计起止日期内进行调料检查的调料次数",
  },
  {
    name: "管道清洗",
    value: "totalPipeCleanNum",
    title: "管道清洗：统计起止日期内进行管道清洗的调料次数",
  },
  {
    name: "管道填充",
    value: "totalPipeFillNum",
    title: "管道填充：统计起止日期内进行管道填充的调料次数",
  },
  {
    name: "养锅",
    value: "totalWokMaintainTimes",
    title: "养锅：统计起止日期内进行养锅的次数",
  },
  {
    name: "快速自动洗锅",
    value: "totalQuickWokWashTimes",
    title: "快速自动洗锅：统计起止日期内进行快速自动洗锅的次数",
  },
  {
    name: "标准自动洗锅",
    value: "totalStandardWokWashTimes",
    title: "标准自动洗锅：统计起止日期内进行标准自动洗锅的次数",
  },
  {
    name: "手动辅助洗锅",
    value: "totalManualWokWashTimes",
    title: "手工辅助洗锅：统计起止日期内进行手工辅助洗锅的次数",
  },
];

// 计算不算今天往前 30 天的日期范围
const getLastMonthDateRange = () => {
  const today = new Date();
  // 获取当前日期的前一天作为结束日期
  const endDate = new Date(today.getTime() - 24 * 60 * 60 * 1000);
  // 获取 30 天前的日期作为起始日期
  const startDate = new Date(endDate.getTime() - 29 * 24 * 60 * 60 * 1000);
  return [startDate, endDate];
};

// 格式化日期
const formatDate = (date: Date | null) =>
  date ? dayjs(date).format("YYYY-MM-DD") : null;

const MyComponent: React.FC = () => {
  const counter = useSelector((state: any) => state.counter.data);
  const [devDate, setDevDate] = useState<any>({
    dev: getLastMonthDateRange(),
    cook: getLastMonthDateRange(),
    main: getLastMonthDateRange(),
  });

  const [allShop, setAllShop] = useState<Merchants>();
  const [selectedValue, setSelectedValue] = useState<
    string | number | null | any
  >(null);
  const [device, setDevice] = useState<Device[]>([]);
  const [cookInfo, setCookInfo] = useState<{ data: Recipe[] }>({ data: [] });
  const [cookType, setCookType] = useState<string>("cook_times");
  const [devInfo, setDevInfo] = useState<Record<string, any>>({});
  const [loveInfo, setLoveInfo] = useState<Record<string, any>>({});
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState<boolean>(true);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const handleChangeId = async (val: string | number) => {
    setSelectedValue(val);
    setDevice([]);
    await Promise.all([
      fetchData(val, devDate.dev[0], devDate.dev[1], "device/statistics").then(
        (data) => data && setDevInfo(data)
      ),
      fetchData(val, devDate.cook[0], devDate.cook[1], "recipes").then(
        (data) => data && setCookInfo({ data })
      ),
      fetchData(
        val,
        devDate.main[0],
        devDate.main[1],
        "maintenance/statistics"
      ).then((data) => data && setLoveInfo(data)),
      fetchData(val, null, null, "devices"),
    ]);
    setPage(1);
  };

  // 数据请求函数
  const fetchData = async (
    id: string | number,
    start: Date | null,
    end: Date | null,
    type: string
  ) => {
    try {
      const { data } = await request.get(`/route/api/merchant/${type}/${id}`, {
        accessToken: 1,
        pageNum: page,
        pageSize: 10,
        ...(start &&
          end && { startDate: formatDate(start), endDate: formatDate(end) }),
        ...(type === "recipes" && {
          limit: 10,
          type: type === "recipes" ? type : undefined,
        }),
      });
      if (type === "devices") {
        setStatus(!status);
        if (page === 1) {
          setDevice(data as Device[]);
        } else {
          setDevice((prevData: any) => {
            return [...(prevData || []), ...((data as Device[]) || [])];
          });
        }
      }

      return data;
    } catch (error) {
      message.error("请求失败");
      console.error(`Error fetching ${type} data:`, error);
      return null;
    }
  };

  const getInitData = async (id = counter?.corpId) => {
    try {
      const { data } = await request.get(
        `/route/api/merchant/getMerchantInCF/${id}`,
        {
          accessToken: 1,
        }
      );
      const firstId = data?.data?.[0]?.merchantId;
      setSelectedValue(firstId);
      setAllShop(data);
      await handleChangeId(firstId);
    } catch (error) {
      message.error("请求失败");
      console.error("Error getting initial data:", error);
    }
  };

  const handleRefresh = () => {
    setRefreshing(true);
    setPage(1);
    getInitData().then(() => {
      setRefreshing(false);
    });
  };

  const renderText = (pullStatus: any, percent: any) => {
    switch (pullStatus) {
      case "pulling":
        return (
          <div>
            下拉即可刷新{" "}
            <span style={{ color: "green" }}>{`${percent.toFixed(0)}%`}</span>
          </div>
        );
      case "canRelease":
        return "释放即可刷新...";
      case "refreshing":
        return "刷新中";
      case "complete":
        return "刷新成功";
      default:
        return "";
    }
  };

  useEffect(() => {
    const container = scrollContainerRef.current;
    if (container) {
      container.addEventListener("scroll", handleScroll);
    }
    return () => {
      if (container) {
        container.removeEventListener("scroll", handleScroll);
      }
    };
  }, [status]);

  const handleScroll = (e: any) => {
    let scrollTop = e.target.scrollTop;
    let scrollHeight = e.target.scrollHeight;
    let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height);
    let currentHeight = scrollTop + offsetHeight;
    if (currentHeight >= scrollHeight - 1) {
      setPage(page + 1);
    }
  };

  useEffect(() => {
    getInitData();
  }, []);

  const getNewData = async () => {
    await fetchData(selectedValue, null, null, "devices");
  };

  useEffect(() => {
    console.log(selectedValue, page, "121212");
    if (!selectedValue) {
      return;
    }
    getNewData();
  }, [page]);


  const handleChanges = (
    dates: any,
    dateSte: string[],
    info: any,
    type: string
  ) => {
    const { range } = info;

    if (range === "start") {
      // 用户选择了开始日期
      setDevDate((prev: any) => ({
        ...prev,
        [type]: dates && dates.length > 0 ? [dates[0], devDate[type][1]] : [],
      }));
    } else if (range === "end") {
      // 用户选择了结束日期
      setDevDate((prev: any) => ({
        ...prev,
        [type]: dates && dates.length > 0 ? [...dates] : [],
      }));
    }
  };
  return (
    <div className="container">
      {/* <Title title="商家" num={allShop?.length} /> */}
      <div style={{ padding: "10px", width: "98%", overflowX: "scroll" }}>
        <Segmented
          onChange={handleChangeId}
          value={selectedValue}
          options={
            allShop?.data?.map((item) => ({
              label: item.merchantName,
              value: item.merchantId,
            })) || []
          }
        />
      </div>
      <Title title="客户设备" num={device?.length} />
      <div className="device-list-container" ref={scrollContainerRef}>
        {device?.length ? (
          <PullToRefreshify
            threshold={1}
            refreshing={refreshing}
            onRefresh={handleRefresh}
            renderText={renderText}
          >
            <div className="scrollable-container">
              {device?.map((item) => (
                <div className="device-item" key={item.cgid}>
                  <div className="device-item-content">
                    <div className="device-item-title">{item.deviceAlias}</div>
                    <span className="device-address">
                      {item.deviceModelCode || ""}
                    </span>
                    <span className="device-info">{item.cgid}</span>
                    <span className="device-address">
                      {item.loginCity || "暂无地址"}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </PullToRefreshify>
        ) : (
          <Empty style={{ width: "98%" }} imageStyle={{ height: 60 }} />
        )}
      </div>
      <Title
        title="客户菜谱"
        num={cookInfo.data.length}
        more={
          <>
            <RangePicker
              disabledDate={(current: dayjs.Dayjs, info: any) => {
                if (!info.from) {
                  const endDate = devDate.cook[1]
                    ? dayjs(devDate.cook[1])
                    : null;
                  if (endDate) {
                    const minStartDate = endDate.subtract(1, "month");
                    return (
                      current.isAfter(endDate) || current.isBefore(minStartDate)
                    );
                  }
                } else {
                  const startDate = devDate.cook[0]
                    ? dayjs(devDate.cook[0])
                    : null;
                  if (startDate) {
                    const maxEndDate = startDate.add(1, "month");
                    return (
                      current.isBefore(startDate) || current.isAfter(maxEndDate)
                    );
                  }
                }

                return false;
              }}
              onCalendarChange={(
                dates: any[] | null,
                dateStrings: string[],
                info: any
              ) => {
                handleChanges(dates, dateStrings, info, "cook");
              }}
              size="middle"
              value={
                devDate.cook[0]
                  ? [dayjs(devDate.cook[0]), dayjs(devDate.cook[1])]
                  : [null, null]
              }
              // onChange={(val: any) => handleDateChange("cook", val)}
            />
            {["cook_times", "cook_spec_copies"].map((item, ind) => (
              <span
                key={item}
                onClick={() => setCookType(item)}
                className={
                  cookType === item ? "span-top10-count" : "span-top10-amount"
                }
              >
                {ind ? "份数Top10" : "次数Top10"}
              </span>
            ))}
            <Button
              key={"search"}
              type="primary"
              className="search-button"
              onClick={() =>
                fetchData(
                  selectedValue!,
                  devDate.cook[0],
                  devDate.cook[1],
                  "recipes"
                ).then((data) => data && setCookInfo({ data }))
              }
            >
              查询
            </Button>
          </>
        }
      />
      {/* <div className="recipe-list-container"> */}
      {cookInfo.data.length ? (
        <div className="scrollable-container recipe-container">
          {cookInfo.data.map((item) => (
            <div className="recipe-item" key={item.recipeName}>
              <div className="recipe-item-content">
                <div className="recipe-item-title">{item.recipeName}</div>
              </div>
              <div className="recipe-item-content">
                <div
                  className="recipe-item-title"
                  style={{ color: "rgb(102,112,133)" }}
                >
                  {cookType === "cook_times"
                    ? `${item.cookTimes}次`
                    : `${item.cookSpecCopies}份`}
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <Empty style={{ width: "98%" }} imageStyle={{ height: 60 }} />
      )}
      {/* </div> */}
      <Title
        title="设备运行统计"
        num={0}
        more={
          <>
            <RangePicker
              disabledDate={(current: dayjs.Dayjs, info: any) => {
                if (!info.from) {
                  const endDate = devDate.dev[1] ? dayjs(devDate.dev[1]) : null;
                  if (endDate) {
                    const minStartDate = endDate.subtract(1, "month");
                    return (
                      current.isAfter(endDate) || current.isBefore(minStartDate)
                    );
                  }
                } else {
                  const startDate = devDate.dev[0]
                    ? dayjs(devDate.dev[0])
                    : null;
                  if (startDate) {
                    const maxEndDate = startDate.add(1, "month");
                    return (
                      current.isBefore(startDate) || current.isAfter(maxEndDate)
                    );
                  }
                }

                return false;
              }}
              size="middle"
              value={
                devDate.dev[0]
                  ? [dayjs(devDate.dev[0]), dayjs(devDate.dev[1])]
                  : [null, null]
              }
              onCalendarChange={(
                dates: any[] | null,
                dateStrings: string[],
                info: any
              ) => {
                handleChanges(dates, dateStrings, info, "dev");
              }}
            />
            <Button
              key={"search"}
              type="primary"
              className="search-button"
              onClick={() =>
                fetchData(
                  selectedValue!,
                  devDate.dev[0],
                  devDate.dev[1],
                  "device/statistics"
                ).then((data) => data && setDevInfo(data))
              }
            >
              查询
            </Button>
          </>
        }
      />
      <div className="chart-container">
        <LineChart data={devInfo.cookTimesTrend || []} title="烹饪次数走势" />
        <LineChart
          data={devInfo.cookSpecCopiesTrend || []}
          title="烹饪份数走势"
        />
      </div>
      <div className="chart-container">
        <LineChart
          type="100"
          data={devInfo.timeCostTrend || []}
          title="烹饪时长走势"
        />
      </div>
      <Title
        title="保养统计"
        num={0}
        more={
          <>
            <RangePicker
              disabledDate={(current: dayjs.Dayjs, info: any) => {
                if (!info.from) {
                  const endDate = devDate.main[1]
                    ? dayjs(devDate.main[1])
                    : null;
                  if (endDate) {
                    const minStartDate = endDate.subtract(1, "month");
                    return (
                      current.isAfter(endDate) || current.isBefore(minStartDate)
                    );
                  }
                } else {
                  const startDate = devDate.main[0]
                    ? dayjs(devDate.main[0])
                    : null;
                  if (startDate) {
                    const maxEndDate = startDate.add(1, "month");
                    return (
                      current.isBefore(startDate) || current.isAfter(maxEndDate)
                    );
                  }
                }

                return false;
              }}
              size="middle"
              value={
                devDate.main[0]
                  ? [dayjs(devDate.main[0]), dayjs(devDate.main[1])]
                  : [null, null]
              }
              onCalendarChange={(
                dates: any[] | null,
                dateStrings: string[],
                info: any
              ) => {
                handleChanges(dates, dateStrings, info, "main");
              }}
            />
            <Button
              key={"search"}
              type="primary"
              className="search-button"
              onClick={() =>
                fetchData(
                  selectedValue!,
                  devDate.main[0],
                  devDate.main[1],
                  "maintenance/statistics"
                ).then((data) => data && setLoveInfo(data))
              }
            >
              查询
            </Button>
          </>
        }
      />
      {/* <div className="maintenance-list-container"> */}
      <div className="scrollable-container recipe-container">
        {titleEnum.map((item, ind) => (
          <div className="recipe-item" key={item.value}>
            <div className="recipe-item-content">
              <div
                className="recipe-item-title"
                style={{ color: "rgba(102, 112, 133, 1)" }}
              >
                {item.name}
                <Popover content={item?.title} title="说明">
                  <InfoCircleOutlined
                    style={{ float: "right", margin: "0px 8px 0px 0px" }}
                  />
                </Popover>
              </div>
            </div>
            <div className="recipe-item-content">
              <div className="recipe-item-title" style={{ fontSize: "16px" }}>
                {loveInfo?.wokMaintenance?.[item.value] ||
                  loveInfo?.ingredientMaintenance?.[item.value] ||
                  0}
              </div>
            </div>
          </div>
        ))}
      </div>
      {/* </div> */}
      <div className="chart-container">
        <LineChart
          mainTitle="保养统计"
          title="完成烹饪"
          title1="完成洗锅"
          data={loveInfo?.wokMaintenance?.successCookDailyData}
          data1={loveInfo?.wokMaintenance?.finishedWashDailyData}
        />
        <LineChart
          mainTitle="养锅次数分析"
          title="养锅"
          title1="完成养锅"
          data={loveInfo?.wokMaintenance?.wokMaintainDailyData}
          data1={loveInfo?.wokMaintenance?.finishedWokMaintainDailyData}
        />
      </div>
      <div className="chart-container">
        <LineChart
          mainTitle="校准与测试分析"
          type="100"
          title="调料校准数量"
          title1="调料检查数量"
          title2="调料测试数量"
          data={loveInfo?.ingredientMaintenance?.seasoningAdjustDailyData}
          data1={loveInfo?.ingredientMaintenance?.seasoningInspectDailyData}
          data2={loveInfo?.ingredientMaintenance?.seasoningTestDailyData}
        />
      </div>
    </div>
  );
};

export default MyComponent;
